define(function(require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    require('/public/js/myservice/common/nav');
    require("/public/js/plugins/select2/select2");
    require('/public/js/myservice/abnormal/abnormal-common');
    require("uploader");
    var util = require("util");
    var ui = require("ui");
    var config = require('/public/js/myservice/config');

    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    angular.module('ViolatedContract', ['ngUI', 'myNav', 'select2', 'AbnormalCommonService'])
            .controller('violatedContractListCtrl', ['$scope', 'abnormalCommonService', 'appservice', function($scope, abnormalCommonService, appservice) {
                appservice.name = '明源云客-违规合同';
                    ui.loading('', '正在加载…');
                    $scope.contracts = [];
                    $scope.sn = 0;
                    $scope.categoryList = null;
                    $scope.filterDataCities = [{
                            areaName: '全部', selected: true, areaId: ''
                        }];
                    //获取合同区域列表
                    abnormalCommonService.getContractAreas(function(data) {
                        $.merge($scope.filterDataCities, data);
                        $scope.$applyAsync();
                    });

                    $scope.changeCity = function(city) {
                        $scope.query.execute();
                    }

                    //查询条件
                    $scope.query = {
                        keyword: '',
                        execute: function(page) {
                            var parms = {keyword: this.keyword};
                            parms.pageIndex = page || 1;
                            parms.pageSize = config.pager().pageSize;
                            parms.sortBy = 'created_on';
                            parms.sortAsc = 'false';

                            //收集过滤条件
                            filterCity = $.grep($scope.filterDataCities, function(o, n) {
                                return o.selected == true;
                            })
                            if (filterCity.length) {
                                parms.areaId = filterCity[0].areaId;
                            }

                            var url = api_prefix + "/violated-contract/get-violated-contract-list&XDEBUG_SESSION_START=netbeans-xdebug";
                            util.myAjax({
                                url: url,
                                type: "GET",
                                cache: false,
                                data: parms,
                                context: this,
                                success: function(json) {
                                    if (json.retCode == 0) {
                                        $scope.contracts = json.data.items;
                                        $scope.$applyAsync();

                                        $scope.startPageIndex = (parms.pageIndex - 1)*10;
                                        $('#pagination').pagination(json.data.total, {
                                            current_page: parms.pageIndex - 1,
                                            num_edge_entries: 1, //边缘页数
                                            num_display_entries: 4, //主体页数
                                            callback: function(page_index, jq) {
                                                //page_index += 1; // 分页控件从 0 开始，后台从 1 开始
                                                $scope.startPageIndex = (page_index - 1)*10;
                                                $scope.query.execute(page_index);
                                                //if (isPagination === true && page_index !== service.pageIndex) {
                                                /*service.pageIndex = page_index;
                                                 service.doQuery(true);*/
                                                //}
                                            },
                                            items_per_page: config.pager().pageSize //每页显示1项
                                        });

                                    } else {
                                        util.alert(json.errMsg);
                                    }
                                },
                                complete: function() {
                                    ui.removeLoading();
                                }
                            });

                        }
                    };

                    $scope.saveContract = function(dialog, dialogScope) {
                        var url = api_prefix + "/violated-contract/save-violated-contract&XDEBUG_SESSION_START=netbeans-xdebug";
                        util.myAjax({
                            url: url,
                            type: "POST",
                            cache: false,
                            data: {item: dialogScope.data.item, attachmentList: dialogScope.data.attachmentList},
                            context: this,
                            success: function(json) {
                                if (json.retCode == 0) {
                                    dialogScope.data.violated_contract_id = json.data;
                                    util.alert('保存成功');
                                } else {
                                    util.alert(json.errMsg);
                                }
                            },
                            complete: function() {
                                ui.removeLoading();
                                $scope.query.execute();
                            }
                        });
                    };
                    $scope.getEmptyContract = function() {
                        return {
                            item: {
                                violated_contract_id: '',
                                contract_code: '',
                                violated_principal: '',
                                principal_name: '',
                                violated_category_id: '',
                                violated_category_id_temp: '',
                                category_name: '',
                                violated_littler_category_id: '',
                                violated_littler_category_id_temp: '',
                                littler_category_name: '',
                                violated_content: '',
                                approver: '',
                                approver_name: '',
                                approve_comment: '',
                                alternative_solution: '',
                            },
                            categoryList: $scope.getCategoryList(),
                            littlerCategoryList: [],
                            attachmentList: [],
                            changeCategory: function(data) {
                                if (typeof (data) == 'undefined') {
                                    return;
                                }
                                data.littlerCategoryList = $scope.getLittlerCategoryList(data.item.violated_category_id);
                                data.item.violated_category_id_temp = data.item.violated_category_id;
                            },
                            changeLittlerCategory: function(data) {
                                if (typeof (data) == 'undefined') {
                                    return;
                                }                                
                                data.item.violated_littler_category_id_temp = data.item.violated_littler_category_id;
                            },                            
                            ddlConfigContract: {
                                allowClear: false,
                                placeholder: '',
                                ajax: {
                                    url: api_prefix + "/contract/get-contract-list-for-violated-contract-select2",
                                    dataType: 'json',
                                    delay: 250,
                                    data: function(term, page) {
                                        return {
                                            keyword: term,
                                            limit: 10
                                        };
                                    },
                                    results: function(data, page) {
                                        return {
                                            results: data.data
                                        };
                                    },
                                    cache: true
                                },
                                escapeMarkup: function(markup) {
                                    return markup;
                                },
                                minimumInputLength: 1,
                                onchange2: function(newVal) {
                                },
                                templateResult: function(data) {
                                    return data;
                                },
                                templateSelection: function(data) {
                                    return data;
                                }
                            },
                            ddlConfigPrincipal: {
                                allowClear: false,
                                placeholder: '',
                                ajax: {
                                    url: api_prefix + "/erp-interface/get-users&XDEBUG_SESSION_START=netbeans-xdebug",
                                    dataType: 'json',
                                    delay: 250,
                                    data: function(term, page) {
                                        return {
                                            keyword: term,
                                            limit: 10
                                        };
                                    },
                                    results: function(data, page) {
                                        return {
                                            results: data.data
                                        };
                                    },
                                    cache: true
                                },
                                escapeMarkup: function(markup) {
                                    return markup;
                                },
                                minimumInputLength: 1,
                                templateResult: function(data) {
                                    return data;
                                },
                                templateSelection: function(data) {
                                    return data;
                                }
                            },
                            ddlConfigApprover: {
                                ajax: {
                                    url: api_prefix + "/erp-interface/get-users&XDEBUG_SESSION_START=netbeans-xdebug",
                                    dataType: 'json',
                                    delay: 250,
                                    data: function(term, page) {
                                        return {
                                            keyword: term,
                                            limit: 10
                                        };
                                    },
                                    results: function(data, page) {
                                        return {
                                            results: data.data
                                        };
                                    },
                                    cache: true
                                },
                                escapeMarkup: function(markup) {
                                    return markup;
                                },
                                minimumInputLength: 1,
                                templateResult: function(data) {
                                    return data;
                                },
                                templateSelection: function(data) {
                                    return data;
                                }
                            },
                            delAttachment: function(data, id) {
                                $(data.attachmentList).each(function(idx, item) {
                                    if (item.document_id.toLowerCase() == id.toLowerCase()) {
                                        data.attachmentList.splice(idx, 1);
                                    }
                                });
                            },
                        };
                    };
                    $scope.onContractEditShow = function(row, dialog, dialogScope) {
                        ui.loading('', '正在加载…');
                        dialogScope.data = $scope.getEmptyContract();

                        dialogScope.$watch('data.item.violated_category_id', function (itemVal) {
                            dialogScope.data.littlerCategoryList = $scope.getLittlerCategoryList(itemVal);
                            dialogScope.data.item.violated_category_id_temp = itemVal;
                        });

                        if (row == null) {
                            // 新增模式
                            ui.removeLoading();
                        }
                        else {
                            // 编辑模式
                            var url = api_prefix + "/violated-contract/get-violated-contract-info&XDEBUG_SESSION_START=netbeans-xdebug";
                            util.myAjax({
                                url: url,
                                type: "GET",
                                cache: false,
                                data: {contractId: row.violated_contract_id},
                                context: this,
                                success: function(json) {
                                    if (json.retCode == 0) {
                                        for (var attr in json.data.item) {
                                            dialogScope.data.item[attr] = json.data.item[attr];
                                        }
                                        dialogScope.data.attachmentList = json.data['attachmentList'];
                                        dialogScope.data.item.violated_category_id_temp = dialogScope.data.item.violated_category_id; 
                                        dialogScope.data.item.violated_littler_category_id_temp = dialogScope.data.item.violated_littler_category_id

                                        $('#contract_code').data('select2').updateSelection({id: dialogScope.data.item['contract_code'], text: dialogScope.data.item['contract_code']});
                                        $('#violated_principal').data('select2').updateSelection({id: dialogScope.data.item['violated_principal'], text: dialogScope.data.item['principal_name']});
                                        $('#approver').data('select2').updateSelection({id: dialogScope.data.item['approver'], text: dialogScope.data.item['approver_name']});

                                    } else {
                                        util.alert(json.errMsg);
                                    }
                                },
                                complete: function() {
                                    dialogScope.$applyAsync();
                                    ui.removeLoading();
                                }
                            });
                        }

                        // 上传控件初始化
                        $('#fileupload').fileupload({
                            dataType: 'json',
                            url: api_prefix + "/common/file/upload-document&XDEBUG_SESSION_START=netbeans-xdebug",
                            add: function(e, data) {
                                // 大小限制
                                if(data.files.length>0){
                                    if(data.files[0].size>config.uploader.max_file_size){
                                        util.alert('文件大小超出'+config.uploader.max_file_size_text+'，无法上传。');
                                        return;
                                    }
                                }
                                data.submit();                                
                                ui.loading('', '正在上传…');
                                $("#fileupload_error").hide();
                            },
                            done: function(e, data) {
                                var res = data.result;
                                if (res.retCode == "0") {
                                    var document = {
                                        document_id: ++$scope.sn,
                                        document_name: data.files[0].name,
                                        document_ext_name: '',
                                        document_path: res.data.path,
                                        business_id: ''
                                    };
                                    dialogScope.data.attachmentList.push(document);
                                    dialogScope.$applyAsync();

                                    $("#fileupload_error").html("");
                                    $("#fileupload_error").hide();
                                } else {
                                    ui.removeLoading();
                                    $("#fileupload_error").html("上传失败:" + res.errMsg);
                                    $("#fileupload_error").show();
                                }
                            },
                            fail: function(e, data) {
                                $("#fileupload_error").html("上传失败:" + data.errorThrown);
                                $("#fileupload_error").show();
                            },
                            always: function(e, data) {
                                ui.removeLoading();
                            }
                        });

                    }
                    $scope.getCategoryList = function() {
                        if ($scope.categoryList == null) {
                            var url = G_CONFIG["api_prefix"] + "/violated-category/get-violated-category-list-for-ddl";
                            util.myAjax({
                                url: url,
                                type: "GET",
                                cache: false,
                                data: '',
                                async: false,
                                context: this,
                                success: function(json) {
                                    if (json.retCode == 0) {
                                        $scope.categoryList = json.data;
                                    } else {
                                        util.alert(json.errMsg);
                                    }
                                }
                            });
                        }

                        return $scope.categoryList;
                    };
                    $scope.getLittlerCategoryList = function(categoryId) {
                        var littlerCategoryList = [];
                        if (categoryId == '') {
                            return littlerCategoryList;
                        }

                        var url = G_CONFIG["api_prefix"] + "/violated-littler-category/get-violated-littler-category-list-for-ddl";
                        util.myAjax({
                            url: url,
                            type: "GET",
                            cache: false,
                            data: {categoryId: categoryId},
                            async: false,
                            context: this,
                            success: function(json) {
                                if (json.retCode == 0) {
                                    littlerCategoryList = json.data;
                                } else {
                                    util.alert(json.errMsg);
                                    littlerCategoryList = [];
                                }
                            }
                        });

                        return littlerCategoryList;
                    }
                    // todo;被两次加载
                    $scope.query.execute();
                }]);
});